package com.example.service.impl;

import com.example.feign.RpcServiceForServiceA;
import com.example.message.Message;
import com.example.respvo.LoginRespVO;
import com.example.service.ICachedHttpReqToResendService;
import com.example.service.IDemoService;
import com.example.reqvo.LoginReqVO;
import com.example.util.FeignMsgUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class IDemoServiceImpl implements IDemoService {
    @Autowired
    private Environment environment;

    @Autowired
    private RpcServiceForServiceA rpcServiceForServiceA;

    @Autowired
    private ICachedHttpReqToResendService iCachedHttpReqToResendService;

    @Override
    public LoginRespVO login(LoginReqVO reqVO) {
        boolean failOverModeOn = isFailOverModeOn();
        /**
         * 故障转移没有开启，则正常调用服务
         */
        if (!failOverModeOn) {
            Message<LoginRespVO> message = rpcServiceForServiceA.login(reqVO);
            LoginRespVO loginRespVO = FeignMsgUtils.extractDataBody(message);
            if (loginRespVO == null) {
                /**
                 * AOP会捕获，返回错误码
                 * {@link com.example.aop.GlobalExceptionHandler}
                 */
                throw new RuntimeException();
            }
            return loginRespVO;
        }

        /**
         * 使用本地数据进行服务，并将请求保存到数据库中
         */
        iCachedHttpReqToResendService.saveLoginReqWhenFailOver(reqVO);

        /**
         * 返回一个 dummy 数据
         */
        return new LoginRespVO();
    }

    private boolean isFailOverModeOn() {
        boolean failOver = false;
        String property = environment.getProperty("failover.mode");
        if (Objects.equals(property, "true")) {
            failOver = true;
        }

        return failOver;
    }
}
